package com.ueboot.weishop.service.customer.impl;

import com.ueboot.weishop.entity.customer.CustomerInfoEntity;
import com.ueboot.weishop.repository.customer.CustomerRepository;
import com.ueboot.weishop.service.customer.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Created by Neel on 2017/9/24.
 */
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerRepository repository;


    @Override
    public Page<CustomerInfoEntity> findBy(Pageable pageable) {
        return repository.findAll(pageable);
    }

    /**
     * 根据关键字查询
     *
     * @param pageable
     * @param keyword
     * @return
     */
    @Override
    public Page<CustomerInfoEntity> findBy(Pageable pageable, String keyword) {
        CustomerInfoEntity entity = new CustomerInfoEntity();
        entity.setName(keyword);
        ExampleMatcher example = ExampleMatcher.matching()
                .withIgnoreNullValues()
                .withMatcher("name", matcher -> matcher.contains())
                .withMatcher("remark", matcher -> matcher.contains());
        return repository.findAll(Example.of(entity, example), pageable);
    }

    @Override
    public CustomerInfoEntity save(CustomerInfoEntity s) {
        return repository.save(s);
    }

    @Override
    public CustomerInfoEntity get(Long id) {
        return repository.findOne(id);
    }

    @Override
    @CacheEvict(key = "'weishop:user:'+#openId", cacheNames = "customer")
    public CustomerInfoEntity findByOpenId(String openId) {
        return repository.findByOpenId(openId);
    }

    @Override
    public void delete(Long id) {
        repository.delete(id);
    }

    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            repository.delete(id);
        }
    }

}
